using System;
using OFX.Aggregator.Infrastructure;
using OFX.Aggregator.WebScraping.Infrastructure;

namespace OFX.Aggregator.WebScraping.Implementation.BESnet.HtmlPageProcessing
{
	public class BESnetStatementPageProcessor : IHtmlPageProcessor
	{
		private readonly string exitUrl;

		public BESnetStatementPageProcessor(string exitUrl)
		{
			this.exitUrl = exitUrl;
		}

		#region Implementation of IHtmlPageProcessor

		public void TestAssumptions(StatementSource source, IWebBrowser webBrowser)
		{
			IHtmlDocument document = webBrowser.Document;

			try
			{
				IHtmlElement pagina = document.GetElementById("PAGINA");
				if (pagina == null)
				{
					throw new AssumptionFailedException(this, "Expected 'PAGINA' element not found in page!");
				}
			}
			catch (InvalidCastException e)
			{
				throw new AssumptionFailedException(this, "Element found was of different type than expected!", e);
			}
		}

		public void ProcessPage(StatementSource source, IWebBrowser webBrowser, IHtmlPageProcessorFinished finished)
		{
			IHtmlDocument document = webBrowser.Document;

			IHtmlElement pagina = document.GetElementById("PAGINA");
			string html = pagina.OuterHtml;

			webBrowser.Navigate(this.exitUrl);

			finished.Finish(html);
		}

		#endregion
	}
}